package cn.hpclub.server.model;

import java.io.Serializable;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.service.RechargeOrderService;

/**
 * 实体类 - 充值缴费支付订单
 * 
 */
@TableBind(tableName = "recharge_order")
public class RechargeOrder extends Model<RechargeOrder> implements Serializable{
    private static final Logger       logger                           = LoggerFactory.getLogger(RechargeOrder.class);
    private static final long         serialVersionUID                 = 5108597504836776215L;
    public static final RechargeOrder dao                              = new RechargeOrder();

    public static final String        ORDER_ID                         = "order_id";
    public static final String        RECHARGE_PHONE                   = "recharge_phone";
    public static final String        RECHARGE_MONEY                   = "recharge_money";
    public static final String        PAY_AMOUNT                       = "pay_amount";
    public static final String        PAY_STATUS                       = "pay_status";
    public static final String        PAY_PLAT                         = "pay_plat";
    public static final String        PAY_TIME                         = "pay_time";
    public static final String        USER_ID                          = "user_id";
    public static final String        USER_NAME                        = "user_name";
    public static final String        USER_PHONE                       = "user_phone";
    public static final String        USER_ORG_ID                      = "user_org_id";
    public static final String        USER_ORG_NAME                    = "user_org_name";
    public static final String        CREATE_TIME                      = "create_time";
    // public static final String IS_HANDLED = "is_handled";
    public static final String        OPERATED_TIME                    = "operated_time";
    public static final String        OPERATED_DESC                    = "operated_desc";
    public static final String        ORDER_STATUS                     = "order_status";
    public static final String        SALE_TYPE                        = "sale_type";
    public static final String        FXSTR                            = "fxstr";

    public static final String        DESC_DETAILS                     = "desc_details";                              // 记录退费接口返回的数据

    // 支付状态
    public static final int           NOT_PAID                         = 0;                                           // 未支付
    public static final int           PAID                             = 1;                                           // 支付成功
    public static final int           FAILED                           = 2;                                           // 支付失败

    public static final int           REFUNDED                         = 5;                                           // 退费成功

    public static final int           REFUND_FAILED                    = 6;                                           // 退费失败

    public static final int           ORDER_SUBMITED                   = 0;

    public static final int           ORDER_NOT_REQUEST                = 1;                                           // 尚未发起办理的订单
    public static final int           ORDER_SUC                        = 5;                                           // 充值成功
    public static final int           ORDER_FAILED                     = 6;                                           // 充值失败
    public static final int           ORDER_REQUEST_NOT_BACK           = 7;                                           // 网络故障
    public static final int           ORDER_REQUEST_RESULT_PARSE_ERROR = 8;                                           // 结果解析异常

    public static final int           RESULT_TYPE_FIRST_RECHARGE       = 1;                                           // 首次充值
    // public static final int RESULT_TYPE_SECOND_RECHARGE = 2; // 二次充值
    // public static final int RESULT_TYPE_SEARCH_UPDATE = 3; // 查询更新
    public static final int           RESULT_TYPE_SEARCH_RECHARGE      = 4;                                           // 查询充值
    public static final String        PAY_CHANNEL                      = "pay_channel";
    public boolean exist(String orderId){
        RechargeOrder order = dao.findFirst("select * from recharge_order where order_id=?", orderId);
        if(order != null){
            return true;
        } else{
            return false;
        }

    }

    public int getUserId(String orderId){
        Record order = Db.findFirst("select user_id from recharge_order where order_id=?", orderId);
        if(order == null){
            return 0;
        }
        if(order.getInt(RechargeOrder.USER_ID) == null){
            return 0;
        }
        return order.getInt(RechargeOrder.USER_ID);
    }

    public String getToken(String orderId){
        Record record = Db.findFirst(
                                     "select token from user_token_map where username = (select user_name from member_org where id =(select user_id from recharge_order where order_id=?))  and is_expired=0",
                                     orderId);
        if(record == null){
            return null;
        }
        return record.getStr("token");
    }

    /**
     * @Title: getRechargeOrderByOrderId
     * @Description:TODO
     * @param orderId
     * @return RechargeOrder
     */
    public RechargeOrder getRechargeOrderByOrderId(String orderId){
        return dao.findFirst("select * from recharge_order where order_id=?", orderId);
    }

    /**
     * @Title: getOrderInfoByOrderId
     * @Description:TODO
     * @param orderId
     * @return RechargeOrder
     */
    public Record getOrderInfoByOrderId(String orderId){
        String sql = "select ro.*,mo.emp_code,o.NumCode from recharge_order ro left join member_org mo on mo.id=ro.user_id left join organization o on o.id=mo.org_id where order_id=?";

        return Db.findFirst(sql, orderId);
    }

    /**
     * @Title: updateData
     * @Description:TODO
     * @param sql
     * @param objects
     *            void
     */
    public int updateData(String sql, Object[] params){

        return Db.update(sql, params);
    }

    /**
     * @Title: updatePayStatusSuc
     * @Description:建行支付成功更新订单支付状态、支付金额等
     * @param orderId
     * @param payStatus
     * @param date
     * @param string
     * @param valueOf
     * @return boolean
     */
    public boolean updatePayStatusSuc(String orderId, int payStatus, Date time, String desc, Double amount){
        // 状态为未支付、支付失败，收到支付成功的通知，才允许更新DB并办理业务。0--未支付，2--支付失败
        String sql = "update recharge_order set pay_status=?,pay_time=?,operated_time=?,operated_desc=?,pay_amount=? where order_id=? and ( pay_status=0 or pay_status=2)";
        int count = Db.update(sql, payStatus, time, time, desc, amount, orderId);
        if(count >= 1){
            return true;
        }

        return false;
    }
    /**
     * @Title: updatePayStatusSuc
     * @Description:建行支付成功更新订单支付状态、支付金额等
     * @param orderId
     * @param payStatus
     * @param date
     * @param string
     * @param valueOf
     * @return boolean
     */
    public boolean updatePayStatusSucV2(String orderId, int payStatus, Date time, String desc, Double amount, int orderStatus){
        String sql = "update recharge_order set pay_status=?,pay_time=?,operated_time=?,operated_desc=?,pay_amount=?,order_status=? where order_id=? and ( pay_status=0 or pay_status=2) and recharge_money=?";
        // 状态为未支付、支付失败，收到支付成功的通知，才允许更新DB并办理业务。0--未支付，2--支付失败
        int count = Db.update(sql, payStatus, time, time, desc, amount, orderStatus, orderId, amount);
        if(count >= 1){
            return true;
        }

        return false;
    }


    /**
     * @Title: updatePayStatusFailed
     * @Description:建行支付失败更新订单支付状态、支付金额等
     * @param orderId
     * @param payStatus
     * @param date
     * @param string
     * @param valueOf
     *            void
     */
    public void updatePayStatusFailed(String orderId, int payStatus, Date time, String desc, Double amount){
        String sql = "update recharge_order set pay_status=?,pay_time=?,operated_time=?,operated_desc=?,pay_amount=? where order_id=? and pay_status="
                + NOT_PAID;

        Db.update(sql, payStatus, time, time, desc, amount, orderId);
    }

    // 操作时间为退费时间
    public boolean updateRefund(String orderId, int payStatus, String desc){
        String sql = "update recharge_order set pay_status=?,desc_details=?,operated_time=? where order_id=?";
        int count = Db.update(sql, payStatus, desc, new Date(), orderId);
        if(count > 0){
            return true;
        }
        return false;
    }

    // 退费时间单独保存，只有退费成功才记，且，只要退费成功，则不再更新数据
    public boolean updateRefund(String orderId, int payStatus, String desc, boolean result){
        String sql = "";
        int count = 0;
        Date time = new Date();
        if(result){// 退费成功，记退费时间
            sql = "update recharge_order set pay_status=?,desc_details=?,operated_time=?,refund_time=? where order_id=? and pay_status !="
                    + REFUNDED;
            count = Db.update(sql, payStatus, desc, time, time, orderId);
        } else{
            sql = "update recharge_order set pay_status=?,desc_details=?,operated_time=? where order_id=? and pay_status !="
                    + REFUNDED;
            count = Db.update(sql, payStatus, desc, time, orderId);
        }
        if(count > 0){
            return true;
        }
        return false;
    }

    public RechargeOrder getOrderStatusInfo(String orderId){
        String sql = "select pay_status,order_status,(case pay_status when 0 then '未支付"
                + "' when 1 then '已支付' when 2 then '支付失败" + Constant.CCB_ORDER_HINT_FOR_PAY_FAILED
                + "' when 5 then '退费成功" + Constant.CCB_ORDER_HINT_FOR_REFUNED
                + "' when 6 then '退费失败' else '出错' end)as pay_state ,(case order_status when 0 then '未知' when 1 then '未发起'  when 5 then '充值成功' when 6 then '充值返回失败'  when 7 then '网络异常'  when 8 then '结果解析失败'else '出错' end)as order_state,operated_desc,desc_details from recharge_order where order_id=?";

        return dao.findFirst(sql, orderId);
    }

    /**
     * @Title: updateOrderStatus
     * @Description:TODO
     * @param orderId
     * @param bossNo
     * @param statusNo
     * @param statusText
     * @param rechargeDesc
     * @return boolean
     */
    public boolean updateOrderStatus(String orderId, String bossNo, int statusNo, String statusText,
            String rechargeDesc){
        Date date = new Date();
        String sql = "";
        int count = 0;
        if(RechargeOrder.ORDER_SUC == statusNo){// 充值成功更新状态，包括充值时间和充值结果说明
            sql = "update recharge_order set boss_no=?,order_status=?,operated_time=?,operated_desc=?,recharge_time=?,recharge_desc=? where order_id=? and order_status!=5";
            count = Db.update(sql, bossNo, statusNo, date, statusText, date, rechargeDesc, orderId);
        } else{// 充值失败更新状态
            sql = "update recharge_order set boss_no=?,order_status=?,operated_time=?,operated_desc=? where order_id=? and order_status!=5";
            count = Db.update(sql, bossNo, statusNo, date, statusText, orderId);
        }

        if(count > 0){
            return true;
        }

        return false;
    }

    /**
     * @Title: getPosIdByOrderId
     * @Description:TODO
     * @param orderId
     * @return String
     */
    public String getPosIdByOrderId(String orderId){
        Record orderRecord = RechargeOrderService.service.getRechargeOrderByOrderId(orderId);

        // "30819c300d06092a864886f70d010101050003818a003081860281806c5ce0ed0655b741d546503f041f1c919bb3bbbf88d7d1549258208619d96df352cd385fb7699a13c4d95c020ab55e5723e64d783180974d6605a6d7db3579b4c8d0751d9e917631e45844a5fd1bf3dba2aa7958b4f823401b46db3274173063b886b1dfd9056235bef55d56811f593e787d8a26103eeaeb3af4ce00a627bc63020111";
        return orderRecord.getStr("pub");

    }
}
